﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orion.Models;
using Orion.MyLib;

namespace Orion.Controllers
{
	[HandleError]
    public class AdvertiesmentController : Controller
    {
    	private AdvertiesRepository m_adRep = new AdvertiesRepository( );

		[Authorize]
        public ActionResult Index( )
        {
			var model = m_adRep.GetAllAdverties( );

			return View( model );
        }	


		//change advertise from being valid or not.
		[Authorize]
		public ActionResult ChangeValid( int? id )
		{
			try
			{
				//validation
				if ( ! id.HasValue )
				{
					return View( "Error" );
				}
				//check if ad.valid is currently true if so nothing should be wrong with changing it to false
				var ad = m_adRep.GetAdvertiseById( id.Value );
				if( ad.Valid == true )
				{
					ad.Valid = false;
					m_adRep.UpdateAdvertise( ad );
					return RedirectToAction("Index");
				}
				//if we get here we know ad is currently false and need to make sure there is space for it on front page.
				var ads = m_adRep.GetAllAdverties();

				var validAds = from a in ads
				               where a.Valid == true
				               select a;
				//if true not space for new ad. max 3 advetise showing at the moment
				if( validAds.Count( ) > 2 )
				{
					return RedirectToAction("Index");
				}

				ad.Valid = true;
				m_adRep.UpdateAdvertise( ad );

				return RedirectToAction("Index");
			}
			catch (Exception ex )
			{
				var log = new Logger();
				log.LogExcepion(ex);
				return View("Error");
			}
			
		}

		[Authorize]
		public ActionResult Create()
		{
			return View( new Adverty( ) );
		}


		[HttpPost]
		[Authorize]
		public ActionResult Create( Adverty ad, HttpPostedFileBase file )
		{
			try
			{
				//validation
				if ( ! ModelState.IsValid )
				{
					return View( ad );
				}
				if( ad.StartDate > ad.EndDate )
				{
					ModelState.AddModelError( "EndDate", "Auglýsing má ekki enda fyrr en hún byrjar" );
					return View( ad );
				}
				//check if file was included
				if (file != null && file.ContentLength > 0 )
				{
					//file saved to hard drive and relative path from web aplication saved
					var fileEnding = file.FileName.Split('.');
					var folder = Path.Combine(Server.MapPath("~/Content/AdvertiesMyndir"));
					var path = Path.Combine(Server.MapPath("~/Content/AdvertiesMyndir"), ad.Title.Trim() + "." + fileEnding[1]);

					//validate folder exist
					if (!Directory.Exists(folder))
					{
						Directory.CreateDirectory(folder);
					}

					file.SaveAs(path);
					ad.Picture = string.Format("/Content/AdvertiesMyndir/{0}.{1}", ad.Title.Trim(), fileEnding[1]);
				}
				ad.AdvDate = DateTime.Now;
				ad.Author = User.Identity.Name;

				m_adRep.AddAdvertise( ad );

				return RedirectToAction( "Index" );
			}
			catch ( Exception ex )
			{
				var log = new Logger( );
				log.LogExcepion( ex) ;
				return View( "Error" );
			}
			
		}

		[HttpGet]
		[Authorize]
		public ActionResult Edit( int? id )
		{
			//validation
			if ( ! id.HasValue )
			{
				return View( "Error" );
			}

			var model = m_adRep.GetAdvertiseById( id.Value );

			return View( model );
		}

		[HttpPost]
		[Authorize]
		public ActionResult Edit( FormCollection form, HttpPostedFileBase file )
		{
			try
			{
				//validation
				if ( ! ModelState.IsValid )
				{
					return View( );
				}

				var ad = new Adverty();
				UpdateModel(ad);

				//ID is returned as string, for some reason need to change it back to int for use.
				int temp;
				if( ! int.TryParse( form["ID"], out temp ) )
				{
					throw new Exception( "ID af auglýsingu tapaðist við tilraun til þess að breyta henni" );
				}
				ad.ID = temp;

				if (file != null && file.ContentLength > 0)
				{
					//file saved to hard drive and relative path from web aplication saved
					var fileEnding = file.FileName.Split('.');
					var folder = Path.Combine(Server.MapPath("~/Content/AdvertiesMyndir"));
					var path = Path.Combine(Server.MapPath("~/Content/AdvertiesMyndir"), ad.ID + "." + fileEnding[1]);

					//validate folder exist
					if (!Directory.Exists(folder))
					{
						Directory.CreateDirectory(folder);
					}

					file.SaveAs(path);
					ad.Picture = string.Format("/Content/AdvertiesMyndir/{0}.{1}", ad.ID , fileEnding[1]);
				}

				m_adRep.UpdateAdvertise( ad );

				return RedirectToAction( "Index" );
			}
			catch ( Exception ex )
			{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View( "Error" );
			}
		}	

		public static string ShowAds( int? id)
		{
			//validation
			if( ! id.HasValue )
			{
				throw new Exception("Reynt var að kalla á showAds með vitlausri færibreytu");
			}
			var adRep = new AdvertiesRepository();
			var ads = adRep.GetAllAdverties();

			var temp = from a in ads
			           where a.Valid == true
			           select a;

			//validate we can not retrive more ads then there are active ads
			var count = temp.Count();
			if( count > id.Value )
			{
				var model = (from a in ads
				             where a.Valid == true
				             select a.Picture).Skip(id.Value).FirstOrDefault();
				return model;
			}

			return "no pic";
		}
    }
}
